package com.loan.web.api;

import com.loan.entity.Perm;
import com.loan.entity.ResponseResult;
import com.loan.service.PermService;
import com.loan.util.Audience;
import com.loan.util.JwtUtil;
import com.loan.vo.PermVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/perm")
public class PermController {

    /**
     * 权限service
     */
    @Autowired
    private PermService permService;

    /**
     * 解密类
     */
    @Autowired
    private Audience audience;


    /**
     * 根据员工表的角色id获取该角色能使用的所有的权限
     * @param jwt 解密
     * @return 权限集合
     */
    @GetMapping("getemp")
    public ResponseResult<List<Perm>> getPermById(@RequestHeader("token") String jwt){
        int empid = JwtUtil.parseJwtForId(jwt, audience);
        return new ResponseResult<>(permService.listByEmpId(empid));
    }

    /**
     * 根据员工的id获取菜单
     * @param jwt
     * @return
     */
    @GetMapping("getmenu")
    public ResponseResult<List<Perm>> getmenuById(@RequestHeader("token") String jwt){
        int empid = JwtUtil.parseJwtForId(jwt, audience);
        return  new ResponseResult<>(permService.getMenuByEmpId(empid));
    }

    @GetMapping("/getpermid/{permid}")
    public ResponseResult<List<Perm>> getpem(@PathVariable int permid){
        Perm perm = permService.getPerm(permid);
        return new ResponseResult(perm);
    }

    @GetMapping("all")
    public ResponseResult<List<PermVO>> getAll(){
        //菜单，子菜单列表
        List<Perm> allMenu = permService.getAllMenu();
        List<PermVO> permVOS = new ArrayList<>();
        allMenu.forEach(p -> {
            if(p.getSubMenu() == 0){
                PermVO permVo = new PermVO();
                permVo.setId(p.getId());
                permVo.setLabel(p.getName());
                permVo.setChildren(new ArrayList<PermVO>());
                permVOS.add(permVo);
            }
        });
        permVOS.forEach(p -> {
            allMenu.forEach( po -> {
                if(po.getSubMenu() == p.getId()){
                    PermVO permVo = new PermVO();
                    permVo.setId(po.getId());
                    permVo.setLabel(po.getName());
                    p.getChildren().add(permVo);
                }
            });
        });
        return new ResponseResult<>(permVOS);
    }


    @RequestMapping("/list")
    @ResponseBody
    public ResponseResult<List<PermVO>> getall(){
        List<Perm> allMenu = permService.getAllMenu();
        return new ResponseResult(allMenu);
    }


    @GetMapping("selectbyperm")
    public ResponseResult<List<Perm>> selectbyperm(@RequestBody Perm perm){
        List<Perm> perms = permService.selectByPerm(perm);
        return new ResponseResult<>(perms);
    }
}
